import { ElMessageBox } from 'element-plus'
import Cookie from 'js-cookie';
import type { Router } from 'vue-router';
import { ViteEnv } from 'script';
import { useUserStoreWithOut, usePermissionStoreWithOut, useTagsViewStoreWithOut } from '../store/index'
import axios from 'axios';
import { TOKEN_KEY } from './const'

declare global {
  interface Window {
    $wujie?: any;
    // 是否存在无界
    __POWERED_BY_WUJIE__?: boolean;
    // 子应用mount函数
    __WUJIE_MOUNT: () => void;
    // 子应用unmount函数
    __WUJIE_UNMOUNT: () => void;
    // 子应用无界实例
    __WUJIE: { mount: () => void };
  }
}

// FsscApp 创建时候配置
export type FsscUtilOption = {
  // 环境变量配置
  env: ViteEnv,
  // 路由实例
  router: Router,
  // appState
  appState: any,
  // passport 验证地址
  passportHost?: string,
  [key: string]: any
}

// 使用时先初始化
export class FsscAppUtil {
  // 配置项
  option: FsscUtilOption;

  constructor() {}

  init(option: FsscUtilOption) {
    this.option = {...option};
    this.option.projectInfo = option.appState.projectInfo
  }

  isPassportLogin() {
    return this.option.env.VITE_LOGIN_TYPE === 'passport'
  }

  clearAuthInfo() {
    const userStore = useUserStoreWithOut();
    // h5模式这样替换
    userStore.setToken('');
    userStore.setUserInfo(undefined);
    Cookie.set(TOKEN_KEY, '')
    if (this.option.env.LOGIN_TYPE == 'custom') {
      const permissionStore = usePermissionStoreWithOut()
      const tagsViewStore =  useTagsViewStoreWithOut()
      let router = this.option.router
      let routes = router.getRoutes()
      routes.forEach((item: any) => {
        if (item.meta.type != 'static' && router.hasRoute(item.name)) {
          router.removeRoute(item.name)
        }
      })
      permissionStore.setIsAddRouters(false)
      tagsViewStore.delAllViews()
    }
  }

  async logout() {
    this.clearAuthInfo()
    if (this.isPassportLogin()) {
      let fromPath = location.href.replace(location.origin, '')
      window.location.href = `${this.option.passportHost}login.html?projectCode=${this.option.projectInfo.code}&projectServer=${encodeURIComponent(
        location.origin)}&fromPath=${fromPath.indexOf('login') > -1 ? '/' : fromPath}&clearSession=true`
    } else {
      // h5模式这样拼
      let fullPath = location.href.replace(location.origin + this.option.router.options.history.base, '')
      this.option.router.push({ path: '/login', query: {redirect: fullPath.indexOf('login') > -1 ? '/' : fullPath } });
    }
  }

  /**
   * @description: 跳转登录页
   * @return {*}
   */
  async login(err: any) {
    let passportHost: string = ''
    if(err.response && !this.option.passportHost) {
      let response = err.response
      if (response.status === 401) {
        this.option.passportHost = response.headers['login-url'] || ''
      }
    }

    if (window.__POWERED_BY_WUJIE__) {
      window.$wujie?.bus.$emit("login", { passportHost });
    } else {
      await this.logout()
    }
  }

  // 获取token信息重定向
  static checkPassportAuthRedirect() {
    let searchStr = location.search;
    if (searchStr.indexOf('token=') === -1) {
      const hashStr = location.hash.replace('#', '');
      if (hashStr.indexOf('token=') !== -1) {
        searchStr = hashStr;
      }
    }
    const params = new URLSearchParams(searchStr) as any;
    const token = params.get('token');
    const fromPath = params.get('fromPath') || '/';
    if (token) {
      Cookie.set('token', token);
      location.href = decodeURIComponent(fromPath);
    }
  }

  // 本本检测
  async versionCheck() {
    const env = this.option.env;
    if (env.MODE === 'development') {
      return;
    }
    const res = await axios.get(`${location.origin}${env.VITE_PUBLIC_PATH == '/' ? '' : env.VITE_PUBLIC_PATH }/version.json?t=${Date.now()}`);
    if (env.VITE_APP_VERSION !== res.data.version) {
      await ElMessageBox.alert('检测到版本更新！', '更新提示', {
        confirmButtonText: '刷新页面',
      })
      if (window.__POWERED_BY_WUJIE__) {
        window.$wujie?.bus.$emit("reload");
      } else {
        window.location.reload();
      }
    }
  }

  async checkMessageToRefresh({ message }: {message?: string}) {
    if (!message) {
      return
    }
    if (message.indexOf('Failed to fetch dynamically imported module') > -1) {
      try {
        await this.versionCheck()
      } catch (err) {
        console.log(err)
      }
    }
  }
}

export const fsscAppUtil = new FsscAppUtil();

export default fsscAppUtil;
